<template>
  <div class="access-logs-container">
    <h1>访问记录</h1>
    <el-table :data="accessLogs" style="width: 100%" v-loading="loading" element-loading-text="加载中...">
      <el-table-column prop="filename" label="文件名" width="250"></el-table-column>
      <el-table-column prop="ip" label="IP地址" width="150"></el-table-column>
      <el-table-column prop="timestamp" label="访问时间" width="200"></el-table-column>
      <el-table-column prop="user_agent" label="用户代理"></el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: center;"
    ></el-pagination>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElLoading, ElMessage } from 'element-plus'

interface AccessLog {
  filename: string
  ip: string
  timestamp: string
  user_agent: string
}

const accessLogs = ref<AccessLog[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取访问记录数据
const fetchAccessLogs = async () => {
  loading.value = true
  try {
    console.log('正在请求访问记录数据...')
    // 构造带分页参数的URL
    const url = `/api/access_logs?page=${currentPage.value}&size=${pageSize.value}`
    console.log('请求URL:', url)
    
    // 使用代理路径访问后端接口
    const response = await fetch(url)
    console.log('API响应状态:', response.status)
    console.log('API响应对象:', response)
    
    if (response.ok) {
      const data = await response.json()
      console.log('接收到的数据:', data)
      accessLogs.value = data.logs || []
      // 确保正确处理分页信息
      total.value = data.pagination?.total || 0
      console.log('总记录数:', total.value)
      console.log('当前页码:', currentPage.value)
      console.log('每页大小:', pageSize.value)
      console.log('分页信息:', data.pagination)
    } else {
      console.error('获取访问记录失败:', response.status)
      console.error('响应文本:', await response.text())
      ElMessage.error('获取访问记录失败: ' + response.status)
    }
  } catch (error) {
    console.error('获取访问记录时发生错误:', error)
    console.error('错误详情:', error.stack)
    ElMessage.error('获取访问记录时发生错误: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchAccessLogs()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchAccessLogs()
}

onMounted(() => {
  fetchAccessLogs()
})
</script>

<style scoped>
.access-logs-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.access-logs-container h1 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}
</style>